<template>
	<image 
		class="user-avatar" 
		:class="avatarClass"
		:src="avatarSrc" 
		:style="avatarStyle"
		@click="onClick" 
		@error="onError"
		:mode="mode"
	></image>
</template>

<script>
import { getUserAvatar, getLocalUserInfo } from '@/utils/avatar.js'

export default {
	name: 'UserAvatar',
	props: {
		// 用户信息对象
		userInfo: {
			type: Object,
			default: () => ({})
		},
		// 头像大小
		size: {
			type: [String, Number],
			default: '80rpx'
		},
		// 头像样式类
		avatarClass: {
			type: String,
			default: ''
		},
		// 图片模式
		mode: {
			type: String,
			default: 'aspectFill'
		},
		// 是否可点击
		clickable: {
			type: Boolean,
			default: true
		}
	},
	computed: {
		avatarSrc() {
			// 优先使用传入的用户信息，否则从本地存储获取
			const user = this.userInfo && Object.keys(this.userInfo).length > 0 
				? this.userInfo 
				: getLocalUserInfo();
			const avatar = getUserAvatar(user);
			console.log('头像路径:', avatar);
			return avatar;
		},
		avatarStyle() {
			const size = typeof this.size === 'number' ? `${this.size}rpx` : this.size;
			return {
				width: size,
				height: size,
				borderRadius: '50%'
			};
		}
	},
	methods: {
		onClick() {
			if (this.clickable) {
				this.$emit('click');
			}
		},
		onError(e) {
			console.warn('头像加载失败:', e);
			this.$emit('error', e);
		}
	}
}
</script>

<style scoped>
.user-avatar {
	display: block;
	background-color: #f0f0f0;
	border: 1rpx solid #e0e0e0;
}
</style>
